import Vue from 'vue'
import axios from 'axios'; 
axios.defaults.withCredentials = true;
Vue.prototype.$axios = axios;
import QS from 'qs'; 
import { Message, Loading } from 'element-ui'
import router from '@/router'  

if (process.env.NODE_ENV == 'development') {
     axios.defaults.baseURL = 'http://localhost:8700/xd';
    Vue.prototype.$baseImgURL= 'http://localhost:8700/xd';
}

// Set 30 seconds request timeout
axios.defaults.timeout = 30000;
axios.defaults.retry = 3; 
axios.defaults.retryDelay = 1000; 

// Create axios instance
axios.interceptors.request.use((config) => {
    if (config.method === 'post' && config.headers['Content-Type'] != "application/json") {
        config.data = QS.stringify(config.data);
    }
    
    return config;
}, (error) => {
    return Promise.reject(error);
});

// Interceptors
axios.interceptors.response.use((res) => {
    if (res.data.stat == '-1009') {
        Message.error('Your login status has expired, please log in again')
        router.replace({
            path: '/login',
        })
        return
    }
    if (!res.data.success) {
        return Promise.resolve(res);
    }
    return res;
},
    (error) => {
        Message.error('Network error, please try again later')
        console.log('Network error', error)
        return Promise.reject(error);
    });

/**
 * Get request
 */
export function get(url, params) {
    return new Promise((resolve, reject) => {
        axios.get(url, {
            params: params
        }).then(res => {
            resolve(res.data);
        }).catch(err => {
            reject(err.data)
        })
    });
}

/**
 * Post request
 */
export function post(url, params, headers = { "Content-Type": "application/json" }) {
    return new Promise((resolve, reject) => {
        axios.post(url, params, {headers})
            .then(res => {
                resolve(res.data);
            })
            .catch(err => {
                reject(err.data)
            })
    })
};
/**
 * Put request
 */
export function put(url, params) {
    return new Promise((resolve, reject) => {
        axios.put(url, params)
            .then(res => {
                resolve(res.data);
            })
            .catch(err => {
                reject(err.data)
            })
    })
};

/**
 * Del request
 */
export function del(url, params) {
    return new Promise((resolve, reject) => {
        axios.delete(url, { data: params })
            .then(res => {
                resolve(res.data);
            })
            .catch(err => {
                reject(err.data)
            })
    })
};

/**
 * Patch request
 */
export function patch(url, params) {
    return new Promise((resolve, reject) => {
        axios.patch(url, params)
            .then(res => {
                resolve(res.data);
            })
            .catch(err => {
                reject(err.data)
            })
    })
};

